package com.example.sandbox.controller.order.uu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.sandbox.controller.order.abstractController.AbstractTransferOrderController;
import com.example.sandbox.controller.order.model.BrazilTransferOrderRequest;
import com.example.sandbox.controller.order.model.DownStreamConstant;
import com.example.sandbox.controller.order.model.TransferOrderRQ;
import com.example.sandbox.dto.ApiRes;
import com.example.sandbox.dto.CS;
import com.example.sandbox.dto.Enum.Currency;
import com.example.sandbox.dto.MchRedisContext;
import com.example.sandbox.dto.domain.TransferOrder;
import com.example.sandbox.helper.BizException;
import com.example.sandbox.helper.MchAndSignCheckHelper;
import com.example.sandbox.util.AmountUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @Author Lierbao
 * @Date 2024/6/14 11:50 下游代付接口
 */

@Slf4j
@RestController
@Api(tags = "巴西代付接口")
public class BrazilTransferOrderController {
    private static final Random RANDOM = new Random();
    @Autowired
    private MchAndSignCheckHelper mchAndSignCheckHelper;
    @Autowired
    private AbstractTransferOrderController abstractTransferOrderController;

    //    @StopWatchTime
    @PostMapping("/api/v1/pay/brazil/transferOrder")
    @ResponseBody
    @ApiOperation("巴西IfCode代付")
    public ApiRes transferOrderIfCode(@RequestBody @Valid BrazilTransferOrderRequest request,
                                      HttpServletRequest httpRequest) {
        long startTime = System.currentTimeMillis();
        log.info("巴西IfCode代付接口入参 [{}]", JSON.toJSONString(request));
        // 验签
        // MchApp mchApp = mchAndSignCheckHelper.mchAndSignAndIPCheck(request, httpRequest, request.getNotifyUrl());
        MchRedisContext mchRedisContext =
            mchAndSignCheckHelper.mchAndSignAndIPCheckRedis(request, httpRequest, request.getNotifyUrl());

        log.info("接口代付验签 耗时:[{}]", System.currentTimeMillis() - startTime);
        // 装配请求参数
        TransferOrderRQ transferOrderRQ = new TransferOrderRQ();
        transferOrderRQ.setOrderId(genTransferOrderId());
        transferOrderRQ.setMchNo(request.getMchNo());
        transferOrderRQ.setAppId(mchRedisContext.getAppId());
        transferOrderRQ.setMchOrderNo(request.getMchOrderNo());
        transferOrderRQ.setIfCode(CS.IF_CODE.BRAZIL_PAY);
        transferOrderRQ.setEntryType(TransferOrder.ENTRY_PIXCRED_CASH);
        transferOrderRQ
                .setAmount(Long.parseLong(AmountUtil.convertDollar2Cent(request.getAmount(), Currency.BRL.getCurrency())));
        transferOrderRQ.setCurrency(Currency.BRL.getCurrency());
        transferOrderRQ.setAccountNo(request.getAccountNo());
        transferOrderRQ.setBankName(null);
        transferOrderRQ.setClientIp("0.0.0.1");
        transferOrderRQ.setTransferDesc(request.getTransferDesc());
        transferOrderRQ.setNotifyUrl(request.getNotifyUrl());

        JSONObject extParams = new JSONObject();
        extParams.put("identityType", request.getIdentityType());
        extParams.put("identityNo", request.getIdentityNo());
        if (StringUtils.isNotBlank(request.getIdentityType()) && "cnpj".equals(request.getIdentityType().trim().toLowerCase())){
            throw new BizException("cnpj is not support");
        }
        transferOrderRQ.setChannelExtra(extParams.toJSONString());

        transferOrderRQ.setExtParam(null);
        transferOrderRQ.setReqTime(request.getReqTime() + "");
        transferOrderRQ.setVersion(DownStreamConstant.VERSION);
        transferOrderRQ.setSign(request.getSign());
        transferOrderRQ.setSignType("MD5");
        log.info("构造代付参数 耗时：[{}]", System.currentTimeMillis() - startTime);
        ApiRes apiRes = abstractTransferOrderController.transferOrderAsyncRequestUpStream(transferOrderRQ, mchRedisContext);

        log.info("[{}]代付下单链路耗时: [{}]ms", request.getMchOrderNo(), System.currentTimeMillis() - startTime);

        return apiRes;
    }

    public static String genTransferOrderId() {

        // 生成时间戳
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        // 生成随机数部分
        long randomPart = RANDOM.nextInt(100000000); // 生成一个9位随机数

        return String.format("%s%s%09d", "T", timestamp, randomPart);
    }


}